package com.hyg.module_health.view.fragment;

import android.app.Activity;
import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.graphics.Outline;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.hyg.lib_base.mainUtils.BluetoothUtils;
import com.hyg.lib_base.mainUtils.StatusBarUtil;
import com.hyg.lib_base.mainUtils.Utils;
import com.hyg.lib_base.orthers.GlideImageLoader;
import com.hyg.lib_common.Base.BaseActivity;
import com.hyg.lib_common.DataModel.YangShengInfo.YangShengData;
import com.hyg.lib_common.DataUtil.UserSPUtils;
import com.hyg.lib_common.Net.CommonHttpUtil;
import com.hyg.lib_common.constant.UrlUtils;
import com.hyg.lib_common.constant.Constants;
import com.hyg.lib_common.constant.FileConstants;
import com.hyg.lib_common.ui.activity.BlueToothListActivity;
import com.hyg.module_health.R;
import com.hyg.module_health.databinding.FragmentHealthBinding;
import com.hyg.module_health.model.datamodel.BannerData;
import com.hyg.module_health.model.datamodel.ShiChenYangShengData;
import com.hyg.module_health.model.datamodel.ShiChenYangShengDataArrayList;
import com.hyg.module_health.model.datamodel.SolarTermData;
import com.hyg.module_health.view.activity.BannerContentActivity;
import com.hyg.module_health.view.activity.HealthAdviseActivity.HealthAdviceListActivity;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Calendar;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Response;

/**
 * 首页养生模块
 */
public class HealthFragment extends Fragment {
    FragmentHealthBinding binding;
    public MyHandler myHandler;
    private ArrayList<ShiChenYangShengData> shiChenYangShengDataArrayList;
    private ArrayList<String> imageList;
    int currentIndex = 0;
    int displayType = 0;
    BluetoothUtils bluetoothUtils;
    BannerData bannerData;

    Activity PareActivity;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentHealthBinding.inflate(inflater);
        init();
        return binding.getRoot();
    }


    @Override
    public void onAttach(@NonNull Activity activity) {
        super.onAttach(activity);

    }

    @Override
    public void onResume() {
        super.onResume();
        StatusBarUtil.setStatusBar(1, PareActivity, getResources().getColor(R.color.white), 0, null, null, true);
        initMainBtnView();
    }

    public void init() {
        initView();
        initData();
    }

    public void initMainBtnView() {
        String hasReport = UserSPUtils.getUserString(PareActivity, FileConstants.HasReport);
        if (hasReport.equalsIgnoreCase("true")) {
            ShowMainBtnView(3);
        } else {
            ShowMainBtnView(2);
        }
    }

    public void initData() {
        myHandler = new MyHandler(PareActivity);
        getRandomYangShengInfo();
        getSolarTermInfo();
        shiChenYangShengDataArrayList = new ShiChenYangShengDataArrayList().getDataList();
        myHandler.sendEmptyMessage(2);
    }

    public void initView() {
        BaseActivity activity = (BaseActivity) PareActivity;
        initShichenTextView();
        binding.rlShichen.setOnClickListener(new View.OnClickListener() {           //12时辰
            @Override
            public void onClick(View v) {
                activity.ToIntent(Constants.PATH_ACTIVITY_MODULE_HEALTH_HOUR, false);
                activity.overridePendingTransition(R.anim.fade, R.anim.hold);
            }
        });
        binding.yangshengyinyue.setOnClickListener(new View.OnClickListener() {            //养生音乐
            public void onClick(View v) {
//                startMusicModle();
                ARouter.getInstance().build(Constants.PATH_ACTIVITY_MODULE_HEALTH_MUSICBED).navigation();
            }
        });
        binding.chakanbaogao.setOnClickListener(new View.OnClickListener() {       //查看报告
            public void onClick(View v) {
                activity.ToIntent(Constants.PATH_ACTIVITY_MODULE_REPORTS_ALLLIST, false);
                activity.overridePendingTransition(R.anim.fade, R.anim.hold);
            }
        });
        binding.chakanjianyi.setOnClickListener(new View.OnClickListener() {       //查看报告
            public void onClick(View v) {
                activity.startActivity(new Intent(PareActivity, HealthAdviceListActivity.class));
                activity.overridePendingTransition(R.anim.fade, R.anim.hold);
            }
        });
        initViewPager();
        getViewpagerData();
    }

    public void initShichenTextView() {
        TextView textView = (TextView) binding.getRoot().findViewById(R.id.tv_suitable);
        textView.setMarqueeRepeatLimit(Integer.MAX_VALUE);
        textView.setFocusable(true);
        textView.setEllipsize(TextUtils.TruncateAt.MARQUEE);
        textView.setSingleLine();
        textView.setFocusableInTouchMode(true);
        textView.setHorizontallyScrolling(true);
        TextView textViewTwo = (TextView) binding.getRoot().findViewById(R.id.tv_taboo);
        textViewTwo.setMarqueeRepeatLimit(Integer.MAX_VALUE);
        textViewTwo.setFocusable(true);
        textViewTwo.setEllipsize(TextUtils.TruncateAt.MARQUEE);
        textViewTwo.setSingleLine();
        textViewTwo.setFocusableInTouchMode(true);
        textViewTwo.setHorizontallyScrolling(true);
    }

    public void ShowMainBtnView(int type) {
        switch (type) {
            case 0:
                binding.lnMainBtn.setWeightSum(1);
                binding.yangshengyinyue.setVisibility(View.GONE);
                binding.chakanjianyi.setVisibility(View.GONE);
                binding.chakanbaogao.setImageResource(R.mipmap.report_large);
                break;
            case 1:
                binding.lnMainBtn.setWeightSum(2);
                binding.yangshengyinyue.setVisibility(View.GONE);
                binding.chakanjianyi.setImageResource(R.mipmap.health_middle_icon);
                binding.chakanbaogao.setImageResource(R.mipmap.report_middle_icon);
                break;
            case 2:
                binding.lnMainBtn.setWeightSum(2);
                binding.chakanjianyi.setVisibility(View.GONE);
                binding.yangshengyinyue.setImageResource(R.mipmap.music_middle_icon);
                binding.chakanbaogao.setImageResource(R.mipmap.report_middle_icon);
                break;
            case 3:
                binding.lnMainBtn.setWeightSum(3);
                binding.chakanjianyi.setVisibility(View.VISIBLE);
                binding.yangshengyinyue.setImageResource(R.mipmap.music_btn_icon);
                binding.chakanjianyi.setImageResource(R.mipmap.health_btn_icon);
                binding.chakanbaogao.setImageResource(R.mipmap.report_btn_icon);
                break;
        }
    }


    public void initViewPager() {
        imageList = new ArrayList<>();
        imageList.add("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fcdn2.lianlianlvyou.com%2Fn%2Ftest%2F20191105105706713.jpeg&refer=http%3A%2F%2Fcdn2.lianlianlvyou.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1617334048&t=4e113a386ff24451345cb11b7747640a");
        imageList.add("https://gimg2.baidu.com/image_search/src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fimages%2F20180801%2F4236b8f796f6422980642a7a24c1a1c2.jpeg&refer=http%3A%2F%2F5b0988e595225.cdn.sohucs.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1617334072&t=d97d25bbab645e8d72eaa05a8098ca57");
        imageList.add("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic3.40017.cn%2Fpoi%2F2015%2F12%2F25%2F10%2F6NRivu_640x320_00.jpg&refer=http%3A%2F%2Fpic3.40017.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1617354371&t=9a22652b63460dc3bc5473d3564e4fae");

        for (int i = 0; i < imageList.size(); i++) {
            View view = new View(PareActivity);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(dip2px(8), dip2px(2));
            params.setMargins(dip2px(5), 0, 0, 0);
            view.setLayoutParams(params);
            view.setBackgroundColor(PareActivity.getResources().getColor(R.color.whiteTranspots));
            binding.lnPointGroup.addView(view, i);
        }
        binding.vpadvert.setImageLoader(new GlideImageLoader(20));
        if (Build.VERSION.SDK_INT > 21) {
            binding.vpadvert.setOutlineProvider(new ViewOutlineProvider() {
                @Override
                public void getOutline(View view, Outline outline) {
                    outline.setRoundRect(0, 0, view.getWidth(), view.getHeight(), 40);
                }
            });
            binding.vpadvert.setClipToOutline(true);
        }
        binding.vpadvert.setImages(imageList);
        binding.vpadvert.setBannerStyle(BannerConfig.NOT_INDICATOR);
        binding.vpadvert.start();
        binding.vpadvert.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                ChangePointColor(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        binding.vpadvert.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                Intent intent = new Intent(PareActivity, BannerContentActivity.class);
                if (bannerData != null && bannerData.getData().size() > 0)
                    intent.putExtra("img", bannerData.getData().get(position).getImg());
                intent.putExtra("content", bannerData.getData().get(position).getContent());
                intent.putExtra("title", bannerData.getData().get(position).getTitle());
                startActivity(intent);
            }
        });
    }

    /**
     * description: 修改viewpager  圆点指示器样式
     *
     * @param position viewpage的currentIndex
     * @time 2021/3/4 9:37
     */
    public void ChangePointColor(int position) {
        position = position % imageList.size();
        if (binding.lnPointGroup.getChildAt(currentIndex) != null) {
            binding.lnPointGroup.getChildAt(currentIndex).setBackgroundColor(PareActivity.getResources().getColor(R.color.whiteTranspots));
        }
        currentIndex = position;
        if (currentIndex < binding.lnPointGroup.getChildCount() && binding.lnPointGroup.getChildAt(currentIndex) != null)
            binding.lnPointGroup.getChildAt(currentIndex).setBackgroundColor(PareActivity.getResources().getColor(R.color.white));
    }


    public void getViewpagerData() {
        CommonHttpUtil.getViewpagerData(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("lgb", "getViewpagerData onFailure: " + e.getMessage());
                myHandler.sendEmptyMessage(5);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.i("lgb", "getViewpagerData onResponse: " + result);
                bannerData = JSONObject.parseObject(result, BannerData.class);
                myHandler.sendEmptyMessage(4);
            }
        });
    }


    /**
     * description: 获取养生信息
     *
     * @author visitant
     * @time 2020/12/8 11:26
     */
    public void getRandomYangShengInfo() {
        BaseActivity activity = (BaseActivity) PareActivity;
        String str_tag = "1";
        FormBody formBody = new FormBody.Builder()
                .add("token", activity.sn.getString("token", ""))//设置参数名称和参数值
                .build();
        activity.sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.getRandomYangShengAddr);
    }


    /**
     * description: 获取养生信息
     *
     * @author visitant
     * @time 2020/12/8 11:26
     */
    public void getSolarTermInfo() {
        BaseActivity activity = (BaseActivity) PareActivity;
        String str_tag = "6";
        activity.sendGetNetwork(str_tag, "", myHandler, UrlUtils.SOLAR_TERM);
    }


    private class MyHandler extends Handler {
        private final WeakReference<Context> reference;
        private BaseActivity activity;

        public MyHandler(Context context) {
            reference = new WeakReference<>(context);
            activity = (BaseActivity) reference.get();
        }

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:                                             //获取用户养生信息并保存
                    JSONObject jsonYS = JSON.parseObject(msg.obj.toString());//获取返回的JSONObject原对象
                    String statusYS = jsonYS.getString("code");
                    String messageYS = jsonYS.getString("message");
                    if (statusYS.equals("200")) {
                        YangShengData data = JSONObject.parseObject(jsonYS.getString("data"), YangShengData.class);
                        if (data.getSeasons().size() > 0) {                             //应季养生
                            binding.yjys.setText("\u3000\u3000" + data.getSeasons().get(0).getSeasonContent().replaceAll("。", "。\r\n\u3000\u3000"));
                            if (!Utils.isEmpty(data.getSeasons().get(0).getSeasonImages())) {
                                Glide.with(activity).load(data.getSeasons().get(0).getSeasonImages()).into(binding.ivYjys);
                            }
                        }
                        if (data.getXiezi().size() > 0) {                               //中医养生
                            binding.xzys.setText("\u3000\u3000" + data.getXiezi().get(0).getIntroductionContent().replaceAll("。", "。\r\n\u3000\u3000"));
                            if (!Utils.isEmpty(data.getXiezi().get(0).getIntroductionImages())) {
                                Glide.with(activity).load(data.getXiezi().get(0).getIntroductionImages()).into(binding.ivXzys);
                            }
                        }
                    } else {
                        Log.i("lgb", "handleMessage: 111ErrorDialog");
                        activity.ErrorDialog(messageYS);
                    }
                    break;
                case 2:                                     //更新12时辰
                    Calendar cal = Calendar.getInstance();
                    int hour = cal.get(Calendar.HOUR_OF_DAY) + 1;
                    int shichen = Math.round(hour / 2);
                    ShiChenYangShengData scysd = shiChenYangShengDataArrayList.get(shichen);
                    Glide.with(activity).load(scysd.getShiChenImageID()).into(binding.ivShichen);
                    binding.tvShichen.setText(scysd.getShiChen_Name());
                    binding.tvSuitable.setText(scysd.getSuitable());
                    binding.tvTaboo.setText(scysd.getTaboo());
                    sendEmptyMessageDelayed(2, 60000);
                    break;
                case 3:

                    break;
                case 4:
                    if (bannerData.getCode() == 200) {
                        imageList.clear();
                        for (BannerData.DataDTO dataDTO : bannerData.getData()) {
                            imageList.add(dataDTO.getImg());
                        }
                        binding.vpadvert.setImages(imageList);
                        binding.vpadvert.setBannerStyle(BannerConfig.NOT_INDICATOR);
                        binding.vpadvert.start();
                    } else {

                        Log.i("lgb", "handleMessage: 4444ErrorDialog");
                        activity.ErrorDialog(bannerData.getMessage());
                    }
                    break;
                case 5:
                    Log.i("lgb", "handleMessage: 5  ErrorDialog");
                    activity.ErrorDialog("服务器错误");
                    break;
                case 6:
                    SolarTermData solarTermData = JSONObject.parseObject(msg.obj.toString(), SolarTermData.class);
                    if (solarTermData.getCode() == 200) {
//                            binding.ivSolarTerm
                        Glide.with(PareActivity).load(solarTermData.getData().getSolarTermImg()).into(binding.ivSolarTerm);
                        binding.tvSolarTermTitle.setText(solarTermData.getData().getSolarTermTitle());
                        binding.tvSolarTermContent.setText("\u3000\u3000" + solarTermData.getData().getSolarTermContent());
                    } else {

                    }
                    break;
            }
        }
    }

    public void startMusicModle() {
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        if (adapter == null) {
            Toast.makeText(PareActivity, "您的手机不支持蓝牙设备!", Toast.LENGTH_SHORT).show();
            return;
        } else if (!adapter.isEnabled()) {
            Intent intent = new Intent(PareActivity, BlueToothListActivity.class);
            intent.putExtra("type", "1");
            startActivity(intent);
            return;
        }
        adapter.getProfileProxy(PareActivity, new BluetoothProfile.ServiceListener() {
            @Override
            public void onServiceConnected(int profile, BluetoothProfile proxy) {
                if (proxy instanceof BluetoothA2dp) {
                    BluetoothA2dp mBluetoothA2dp = (BluetoothA2dp) proxy;
                    try {
                        Class<?> bluetoothA2dp = Class.forName("android.bluetooth.BluetoothA2dp");
                        Method getActiveDevice = bluetoothA2dp.getMethod("getActiveDevice");
                        BluetoothDevice activeDevice = (BluetoothDevice) getActiveDevice.invoke(mBluetoothA2dp);
                        Log.i("lgb", "onServiceConnected: " + activeDevice.getName());
                        if (activeDevice != null && BluetoothUtils.isMusicProduct(activeDevice)) {
                            ARouter.getInstance().build(Constants.PATH_ACTIVITY_MODULE_HEALTH_MUSICBED).navigation();
                            PareActivity.overridePendingTransition(com.hyg.lib_common.R.anim.fade, com.hyg.lib_common.R.anim.hold);
                        } else {
                            Intent intent = new Intent(PareActivity, BlueToothListActivity.class);
                            intent.putExtra("type", "1");
                            startActivity(intent);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("lgb", "onServiceConnected2222: Exception");
                        Intent intent = new Intent(PareActivity, BlueToothListActivity.class);
                        intent.putExtra("type", "1");
                        startActivity(intent);
                    }
                }
            }

            @Override
            public void onServiceDisconnected(int profile) {
                Log.i("lgb", "onServiceDisconnected: ");
            }
        }, BluetoothProfile.A2DP);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        myHandler.removeCallbacksAndMessages(null);
    }

    public int dip2px(float dpValue) {
        final float scale = PareActivity.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        Log.i("lgb", "onAttach: " + (getActivity() == null));
        PareActivity=getActivity();
    }
}